from flask import Blueprint,json,jsonify,request,g
from flask_restful import reqparse,Api,Resource,marshal
from models.courses import *
from models.users import *
from common.utlis.my_output_json import custom_output_json
from common.utlis.name_list import *
from common.utlis.login_utlis import login_required
from common.utlis.jwt_util import check_token
from models.permissiones import Roles

courses_bp = Blueprint('courses', __name__, url_prefix='/course')

api = Api(courses_bp)

# 统一后端返回给前端的数据结构
@api.representation('application/json')
def output_json(data, code,headers=None):
    resp = custom_output_json(data, code)
    return resp


# 获取全部的标签
class CourseTagInfo(Resource):
    def get(self):
        try:
            tag = CourseTag.query.all()
            data = marshal(tag,coursetag_fields)
            return {'message':'获取标签成功', 'code':200, 'data':data}
        except Exception as e:
            print('错误>>>', e)
            return {'message':'获取标签失败', 'code':400}


class CourseInfo(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('tag_id')
        parser.add_argument('free')
        parser.add_argument('online')
        parser.add_argument('sort')
        args = parser.parse_args()
        tag_id = args.get('tag_id')
        free = args.get('free')
        online = args.get('online')
        sort = args.get('sort')
        print('123456', tag_id, free, online, sort)

        # 获取全部数据
        course_and_tag = CourseandTag.query.all()
        if tag_id != None:  # 是否根据标签过滤
            course_and_tag = CourseandTag.query.filter_by(tag_id=tag_id).all()


        print("数据", course_and_tag)
        temp = []
        for i in course_and_tag:
            course = Course.query.filter_by(id=i.course_id).first()

            if free != None:  # 不满足条件，跳过
                if int(free) != course.cate_type:
                    continue

            if online != None:  # 不满足条件，跳过
                if int(online) != course.course_status:
                    continue

            course = marshal(course, course_fields)
            course = json.loads(json.dumps(course))

            type_data = CategoryTable.query.filter_by(id=course["cate_type"]).first()
            course["type_name"] = type_data.type_name
            temp.append(course)

        if sort:  # 排序
            temp = self.order_data(sort, temp)

        return jsonify(message="ok！", code=200, data=temp)

    @staticmethod
    def order_data(sort, data):
        if int(sort) == 1:  # 最新
            for i in range(1, len(data)):
                for j in range(0, len(data) - i):
                    if data[j].get("create_time") < data[j + 1].get("create_time"):
                        queryset_data = data[j]
                        data[j] = data[j + 1]
                        data[j + 1] = queryset_data
        else:  # 学习人数
            for i in range(1, len(data)):
                for j in range(0, len(data) - i):
                    if data[j].get("learner") < data[j + 1].get("learner"):
                        queryset_data = data[j]
                        data[j] = data[j + 1]
                        data[j + 1] = queryset_data
        return data


class CourseinfoOne(Resource):
    @login_required
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('cid')
        args = parser.parse_args()
        cid = args.get('cid')
        # TODO 获取当前登录的用户id,
        # 判断当前用户的级别,若不是会员, 没有权限请先升级成为会员
        # try:
        #     vip = VipModel.query.filter_by(user=g.user_id).first()
        #     print('vip',vip)
        # except Exception as e:
        #     print('e', e)
        #     return jsonify(message="用户不存在", code=401)
        # # 会员用户可以观看免费的,普通用户只能观看免费的视频
        # # role_id = vip.level # 当前用户的等级
        # # 获取当前用户等级的权限
        # role = Roles.query.filter_by(id=vip.level).first()
        # print('role', role)
        # # 是权限的列表
        # permissons = role.permission
        # # 获取当前请求的url
        # if str(request.url) not in permissons:
        #     return jsonify(message="没有权限,请升级会员", code=403)
        try:
            course = Course.query.filter_by(id=cid).first()
            chapters = Chapters.query.filter_by(course=course.id).all()
            course = marshal(course, course_fields)
            chapters = marshal(chapters, chapters_fields)

            for i in chapters:
                sections = Sections.query.filter_by(chapters=i['id']).all()
                sections = json.loads(json.dumps(marshal(sections,sections_fields)))
                i['sections_dict'] = sections

            data_ = {
                'data':course,
                'chapters':chapters,
            }
            return jsonify(message="ok！", code=200, data=data_)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='获取失败', code=204)


class SectionsInfo(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('sid')
        args = parser.parse_args()
        sid = args.get('sid')

        try:
            sections = Sections.query.filter_by(id=sid).first()
            sections_dict = json.loads(json.dumps(marshal(sections, sections_fields)))
            return jsonify(code=200,message='获取小节成功', data=sections_dict)
        except Exception as e:
            print('错误', e)
            return jsonify(message='获取错误', code=204)


# 关注课程
class AttentionTableInfo(Resource):
    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument('cid')
        parser.add_argument('token')
        # parser.add_argument('is_attention')
        args = parser.parse_args()
        cid = args.get('cid')
        token = args.get('token')
        # is_attention = args.get('is_attention')

        print('课程的id', cid)
        print('token>>>>', token)
        # print('关注的状态', is_attention)

        if token:
            # 校验token
            try:
                payload = check_token(token)
            except Exception as e:
                print('e>>>', e)
                return jsonify(message='请先登录', code=401)
            # user_id = payload['user_id']

            try:
                course = Course.query.filter_by(id=cid).first()
                if course.is_attention == 1:
                    # 取消关注
                    Course.query.filter_by(id=cid).update({'is_attention':0,'attention':course.attention-1})
                    db.session.commit()
                    return jsonify(message='取消关注成功', code=200, data={'attention':course.attention})
                else:
                    # 关注
                    Course.query.filter_by(id=cid).update({'is_attention': 1, 'attention': course.attention + 1})
                    db.session.commit()
                    return jsonify(message='关注成功', code=200, data={'attention':course.attention})
            except Exception as e:
                print('错误>>', e)
                return jsonify(message='服务器错误', code=500)



class CourseLearnStatus(Resource):
    def get(self):
        """获取用户学习进度"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('cid')
        args = parser.parse_args()
        token = args.get('token')
        cid = args.get('cid')
        if token:
            try:
                payload = check_token(token)
            except Exception as e:
                return  jsonify(message="请先登录", code=401)
            user_id= payload['id']
        # 获取课程额章节
        course_chapters = Chapters.query.filter_by(course=cid).all()

        # 序列化输出
        course_chapters = json.loads(json.dumps(marshal(course_chapters, chapters_fields)))
        # TODO 获取每个章节下的小节信息.需要保存的是学过的小节信息
        data_ = [] # 存放学过的章节
        """
        [
            {
                'id':1,
                'chapter_title':"环境搭建",
                'sections_list':[
                    {
                        'id': 小结1,
                        'title':小节名
                    }
                ]
            }
        ]
        """
        for chapter in course_chapters:
            # 获取小节
            sections = Sections.query.filter_by(chapters=chapter.id, is_learned=1).all()
            # TODO 章节下所有的小节数和学过的小节数对比, 值一样说明章节学完, 否则没学完
            if len(chapter.sections) == len(sections):
                sections = json.loads(json.dumps(marshal(sections, sections_fields)))
                chapter['sections_list'] = sections
                data_.append(chapter)

        return jsonify(message='ok', data=data_)


# 获取所有的标签
api.add_resource(CourseTagInfo, '/coursetag')

# 获取全部的课程
api.add_resource(CourseInfo, '/courseall')

# 获取单个课程信息
api.add_resource(CourseinfoOne, '/courseinfo')

# 获取视频
api.add_resource(SectionsInfo, '/sectionvideo')

# 关注课程
api.add_resource(AttentionTableInfo, '/attention')

# 学习进度
api.add_resource(CourseLearnStatus,'/learninfo')